package org.hydrakyoufeng.stuplatform.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.math.MathContext;
import java.time.Duration;
import java.time.Instant;

@Slf4j
@Aspect
@Configuration
public class ServiceLogAspectConfig {

    @Value("${server.port}")
    private String port;

    @Pointcut("execution(* org.hydrakyoufeng.stuplatform.service.impl.*.*(..))")
    public void serviceLog() {

    }

    /**
     * 环绕通知
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("serviceLog()")
    public Object doAroundService(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        try {
            Instant instStart = Instant.now();
            Object object = proceedingJoinPoint.proceed();
            Signature signature = proceedingJoinPoint.getSignature();
            Instant instEnd = Instant.now();
            long timeDifference = Duration.between(instStart, instEnd).toMillis();
            BigDecimal divideUnsigned = BigDecimal.valueOf(timeDifference)
                    .divide(BigDecimal.valueOf(1000L), new MathContext(2));

            log.info("-------------------start  {}  端口 {} -----------------", Thread.currentThread().getName(),port);
            log.info("执行class_method={}, args={}",
                    signature.getDeclaringTypeName() + "." + signature.getName(), proceedingJoinPoint.getArgs());
            log.info("{}请求耗时={}秒", Thread.currentThread().getName(), divideUnsigned);
            if (object != null) {
                log.info("返回值={}", object);
            }
            log.info("-------------------{}  end-----------------", Thread.currentThread().getName());
            return object;
        } catch (Throwable throwable) {
            log.error("发现异常：class_method={}, args={}, 异常信息:{}", proceedingJoinPoint
                            .getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName(),
                    proceedingJoinPoint.getArgs(), throwable);
            throw throwable;
        }
    }
}

